package com.peakproducts;

import net.rim.device.api.system.Characters;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;

public class PeakField extends Field {

	private int backgroundColour = 0x000000;
	private int highlightColour;
	private int fieldWidth;
	private int fieldHeight;
	private String text;
	private int padding = 6;

	public PeakField(String text, int bgColor, int width, int height) {
		super(Field.FOCUSABLE);
		this.text = text;
		this.highlightColour = bgColor;
		Font defaultFont = Font.getDefault();
		if (height == 0)
			fieldHeight = defaultFont.getHeight() + padding;
		else
			fieldHeight = height;
		if (width == 0)
			fieldWidth = defaultFont.getAdvance(text) + (padding * 2);
		else {
			fieldWidth = width;
		}
		this.setPadding(2, 2, 2, 2);
	}

	public PeakField(String text) {
		this(text, 0x330033, 0, 0);
	}

	protected boolean navigationClick(int status, int time) {
		fieldChangeNotify(1);
		return true;
	}

	protected void onFocus(int direction) {
		backgroundColour = highlightColour;
		invalidate();
	}

	protected void onUnfocus() {
		backgroundColour = 0x000000;
		invalidate();
	}

	public int getPreferredWidth() {
		return fieldWidth;
	}

	public int getPreferredHeight() {
		return fieldHeight;
	}

	protected void layout(int arg0, int arg1) {
		setExtent(getPreferredWidth(), getPreferredHeight());
	}

	protected void drawFocus(Graphics graphics, boolean on) {

	}

	protected void fieldChangeNotify(int context) {
		try {
			this.getChangeListener().fieldChanged(this, context);
		} catch (Exception e) {
		}
	}

	public boolean keyChar(char key, int status, int time) {
		boolean retval = false;
		if (key == Characters.ENTER || key == Characters.SPACE) {
			fieldChangeNotify(1);
			retval = true;
		} else {
			retval = super.keyChar(key, status, time);
		}
		return retval;
	}

	protected void paint(Graphics graphics) {
		graphics.setColor(backgroundColour);
		graphics.fillRoundRect(0, 0, fieldWidth, fieldHeight, 8, 8);
		graphics.setColor(Color.BLACK);
		graphics.drawRoundRect(0, 0, fieldWidth, fieldHeight, 8, 8);
		graphics.setColor(Color.WHITE);
		graphics.drawText(text, padding - 1, padding / 2 + 1);
	}

	public String getLabel() {
		// TODO Auto-generated method stub
		return text;
	}

}